﻿using Microsoft.Extensions.Logging;
using Share;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Net.Http.Json;
namespace CryptLib;

public class AESService
{
    //private readonly AppParams _appParams;
    private readonly ILogger<AESService> _logger;

    public AESService(ILogger<AESService> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// AES加密数据
    /// </summary>
    /// <param name="data">被加密的明文</param>
    /// <param name="key">密钥</param>
    /// <param name="iv">偏移量</param>
    /// <returns>被加密的内容，经base64编码</returns>
    public string Encrypt(string data, string key, string iv)
    {
        try
        {
            using (Aes aes = Aes.Create())
            {
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.None;
                //aes.KeySize = 32; // 根据密钥长度设置
                aes.BlockSize = 128; // 根据块大小设置

                // 设置密钥和初始化向量
                aes.Key = Encoding.UTF8.GetBytes(key);
                //aes.Key = Convert.FromHexString(key);
                aes.IV = Encoding.UTF8.GetBytes(iv);

                // 计算数据长度和块大小
                byte[] dataBytes = Encoding.UTF8.GetBytes(data);
                int blockSize = aes.BlockSize / 8;
                int plaintextLength = dataBytes.Length;

                if (plaintextLength % blockSize != 0)
                {
                    plaintextLength += (blockSize - (plaintextLength % blockSize));
                }

                byte[] plaintext = new byte[plaintextLength];
                Array.Copy(dataBytes, plaintext, dataBytes.Length);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                    }

                    byte[] encrypted = ms.ToArray();
                    return Convert.ToBase64String(encrypted);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
            return string.Empty;
        }
    }

    public string Encrypt<T>(T data, string key, string iv) where T : class
    {
        var plainText = JsonSerializer.Serialize(data);
        return Encrypt(plainText, key, iv);
    }

    /// <summary>
    /// 采用SHA1数据摘要
    /// </summary>
    /// <param name="data"></param>
    /// <returns>添加盐值的数据摘要</returns>
    public string MessageDigestWithSalt(string data, string salt)
    {
        try
        {
            using (SHA1 sha1 = SHA1.Create())
            {
                byte[] dataBytes = Encoding.UTF8.GetBytes(data + salt);
                byte[] hashBytes = sha1.ComputeHash(dataBytes);


                StringBuilder hexString = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    //b.ToString("x2") 确保第个字节都是两位数（高
                    hexString.Append(b.ToString("x2"));
                }
                return hexString.ToString();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
            return "";
        }
    }

    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="data">加密后的字符串</param>
    /// <param name="key">密钥</param>
    /// <param name="iv">偏移量</param>
    /// <returns>解密后的字符串</returns>
    public string Decrypt(string data, string key, string iv)
    {
        try
        {
            byte[] encrypted = Convert.FromBase64String(data);

            using (Aes aes = Aes.Create())
            {
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.None;
                //aes.KeySize = 128; // aes 密钥长度只能是 129 196 256 bits ,1个字符是4bit
                aes.BlockSize = 128; // 根据块大小设置

                byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
                byte[] keyBytes = Encoding.UTF8.GetBytes(key);

                aes.Key = keyBytes;
                aes.IV = ivBytes;

                using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                {
                    using (MemoryStream memoryStream = new MemoryStream(encrypted))
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader streamReader = new StreamReader(cryptoStream, Encoding.UTF8))
                            {
                                return streamReader.ReadToEnd();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("解密失败：" + ex.Message);
            return string.Empty;
        }
    }
}
